package com.easytouch;

import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/* 本代码仅供参考，不对稳定性负责 */
public class SerialPort {
	private static final String TAG = "SerialPort";

	/*
	 * Do not remove or rename the field mFd: it is used by native method close();
	 */
	private FileDescriptor mFd;
	private FileInputStream mFileInputStream;
	private FileOutputStream mFileOutputStream;
	public SerialPort(File device, int baudrate) throws SecurityException, IOException {
		this(device, baudrate, 8, 1, 'n', 0);
	}
	public SerialPort(File device, int baudrate, int databits, int stopbits, char parity) throws SecurityException, IOException {
		this(device, baudrate, databits, stopbits, parity, 0);
	}

	/**
	 *
	 * @param device     File
	 * @param baudrate
	 * @param databits  7， 8
	 * @param stopbits  1， 2
	 * @param parity    'n'无校验，'o' 奇校验， 'e' 偶校验 // 由于无测试测试设备, 目前只支持 'n'
	 * @param timeout   范围：0-255. 0 代表阻塞，不超时返回。 1-255 代表 0.1-25.5秒， 读超时返回 -1
	 * @throws SecurityException
	 * @throws IOException
	 */
	public SerialPort(File device, int baudrate, int databits, int stopbits, char parity, int timeout) throws SecurityException, IOException {

		/* Check access permission */
//		if (!device.canRead() || !device.canWrite()) {
//			try {
//				/* Missing read/write permission, trying to chmod the file */
//				Process su;
//				su = Runtime.getRuntime().exec("su");
//				String cmd = "chmod 777 " + device.getAbsolutePath() + "\n"
//						+ "exit\n";
//				su.getOutputStream().write(cmd.getBytes());
//				if ((su.waitFor() != 0)) {
//					Log.e(TAG, "root failed!");
//				}
//				if  (!device.canRead() || !device.canWrite()) {
//					throw new SecurityException();
//				}
//			} catch (Exception e) {
//				Log.e(TAG, "No permission: " + device.getAbsolutePath() );
//				e.printStackTrace();
//				throw new SecurityException();
//			}
//		}
		mFd = open(device.getAbsolutePath(), baudrate, databits, stopbits, parity, timeout);
		if (mFd == null) {
			Log.e(TAG, "native open returns null");
			throw new IOException();
		}
		mFileInputStream = new FileInputStream(mFd);
		mFileOutputStream = new FileOutputStream(mFd);
	}

	// Getters and setters
	public InputStream getInputStream() {
		return mFileInputStream;
	}

	public OutputStream getOutputStream() {
		return mFileOutputStream;
	}

	// JNI
	private native static FileDescriptor open(String path, int baudrate, int databits,int stopbits,char parity, int timeout);
	public native void close();
	static {
		System.loadLibrary("SerialPort-svt");
	}
}
